﻿using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Msagl.Core.Layout;
using Microsoft.Msagl.Core.Geometry.Curves;
using Microsoft.Msagl.Core.Geometry;
using Microsoft.Msagl.Core.Routing;
using Microsoft.Msagl.Routing;
using System.Windows;
using System.Threading;
using MPoint = Microsoft.Msagl.Core.Geometry.Point;
using MNode = Microsoft.Msagl.Core.Layout.Node;
using Timtopia.DGMLPosterView;
using System.Windows.Media;

namespace UnitTestProject1
{
    [TestClass]
    public class RoutingTests
    {
        [TestMethod]
        public void TestRouting()
        {
            var graph = new GeometryGraph();
            var nodeSize = new MPoint(10, 10);
            double r = 2;
            var a = new MNode(new RoundedRect(new Rectangle(10, 20, nodeSize), r, r), "a");
            var b = new MNode(new RoundedRect(new Rectangle(40, 20, nodeSize), r, r), "b");
            var c = new MNode(new RoundedRect(new Rectangle(70, 20, nodeSize), r, r), "c");
            graph.Nodes.Add(a);
            graph.Nodes.Add(b);
            graph.Nodes.Add(c);
            var g = new Cluster();
            g.AddChild(b);
            g.BoundaryCurve = new RoundedRect(new Rectangle(30, 10, new MPoint(30, 30)), r, r);
            graph.RootCluster = new Cluster(new[] { a, b }, new[] { g });
            var edge = new Edge(a, c);
            graph.Edges.Add(edge);
            graph.Edges.Add(new Edge(a, c));
            graph.Edges.Add(new Edge(b, c));
            graph.Edges.Add(new Edge(a, g));

            var intersections = GetEdgeIntersections(r, g, edge);
            Assert.IsTrue(intersections.Length > 0, "before routing edge between a and c should is a straight line though the cluster containing b");
            
            var settings = new BundlingSettings();
            settings.EdgeSeparation = 2;
            var route = new SplineRouter(graph, 2, 4, Math.PI / 6, settings);
            route.Run();

            intersections = GetEdgeIntersections(r, g, edge);
            Assert.AreEqual(0, intersections.Length, "edge between a and c should not overlap the cluster containing b");
            
            //DebugViewer.ViewRouting(graph, 5);
        }

        private static System.Windows.Point[] GetEdgeIntersections(double r, Cluster g, Edge edge)
        {
            var edgeGeometry = edge.ToGeometry();
            var clusterBounds = g.BoundaryCurve.BoundingBox;
            var clusterGeometry = new RectangleGeometry(new Rect(clusterBounds.Left, clusterBounds.Bottom, clusterBounds.Width, clusterBounds.Height), r, r);
            var intersections = GeometryHelper.GetIntersectionPoints(edgeGeometry, clusterGeometry);
            return intersections;
        }
    }
}
